//
//  NSObject+LBHTTPSessionManager.m
//  LBNetworking
//
//  Created by WuShiHai on 19/5/30.
//  Copyright (c) 2019 Lebbay. All rights reserved.
//

#import "NSObject+LBHTTPSessionManager.h"
#import <objc/runtime.h>
#import <AFNetworking/AFNetworking.h>

static char NSObjectWLRequestTasksKey;
static char NSObjectWLTaskDidComleteHandlesKey;

@interface NSObject ()

@property (nonatomic, strong) NSMutableArray *wl_requestTasks;
@property (nonatomic, copy) void(^wl_taskDidComleteHandle)(void);

@end

@implementation NSObject (LBHTTPSessionManager)

- (void)cancelAllTask{
    [self.wl_requestTasks makeObjectsPerformSelector:@selector(cancel)];
}

- (void)addTask:(NSURLSessionTask *)task{
    if (task == nil) {
        return;
    }
    
    if (self.wl_requestTasks == nil) {
        self.wl_requestTasks = [@[] mutableCopy];
    }
    
    [self observeClearNetWorkingTask:task];
    [self.wl_requestTasks addObject:task];
}

- (void)tasksDidComplete:(void(^)(void))completeHandle{
    self.wl_taskDidComleteHandle = completeHandle;
}

- (NSInteger)numberOfTasks{
    return self.wl_requestTasks.count;
}

- (void)removeNSURLSessionTaskObserver{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//任务完成后移除
- (void)observeClearNetWorkingTask:(NSURLSessionTask *)task{
    
    __weak __typeof(&*self) weakSelf = self;
    __block __weak id<NSObject> observer = [[NSNotificationCenter defaultCenter] addObserverForName:AFNetworkingTaskDidCompleteNotification object:task queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) {
        
        if (notification.object && [notification.object isKindOfClass:[NSURLSessionTask class]]) {
            [weakSelf.wl_requestTasks removeObject:task];
            if (weakSelf.wl_requestTasks.count == 0) {
                weakSelf.wl_taskDidComleteHandle?weakSelf.wl_taskDidComleteHandle():nil;
            }
        }
        
        [[NSNotificationCenter defaultCenter] removeObserver:observer];
        
    }];
    
}

- (void)setWl_requestTasks:(NSMutableArray *)wl_requestTasks{
    objc_setAssociatedObject(self, &NSObjectWLRequestTasksKey, wl_requestTasks, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSMutableArray *)wl_requestTasks{
    return objc_getAssociatedObject(self, &NSObjectWLRequestTasksKey);
}

- (void)setWl_taskDidComleteHandle:(void (^)(void))wl_taskDidComleteHandle{
    objc_setAssociatedObject(self, &NSObjectWLTaskDidComleteHandlesKey, wl_taskDidComleteHandle, OBJC_ASSOCIATION_COPY);
}
- (void (^)(void))wl_taskDidComleteHandle{
    return objc_getAssociatedObject(self, &NSObjectWLTaskDidComleteHandlesKey);
}


@end
